<template>
    <div class="menu-page">
        <div class="top-group">
            <div class="top-select" @click="dateSelectionPopUp = true">
                <p>{{ year }}年{{ month }}月{{ day }}日</p>
                <van-icon name="arrow-down" />
            </div>
            <div class="top-select" @click="outpatientPopUps = true">
                <p>{{ outpatient }}</p>
                <van-icon name="arrow-down" />
            </div>
            <div v-if="[7, 19].includes(userinfo.group_id)" class="top-select" @click="salesmanPopUpWindow = true">
                <p>{{ salesman }}</p>
                <van-icon name="arrow-down" />
            </div>
            <div class="topup" @click="reset">
                <van-icon name="replay" />
            </div>
        </div>
        <div class="table-top">
            <div>日期</div>
            <div>门诊</div>
            <div>业务员</div>
            <div>状态</div>
        </div>
        <div class="table-wrapper">
            <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="loadpage">
                <div
                    class="table-row"
                    :style="{ marginTop: isFirstDifferentDate(item.createtime) ? '20px' : '0' }"
                    v-for="item in list"
                    :key="item.id"
                    @click="detail(item)"
                >
                    <div>{{ formatTime(item.createtime, "YYYY-MM-DD") }}</div>
                    <div>{{ item.outpatient.title }}</div>
                    <div>{{ item.user.nickname }}</div>
                    <div class="action" :style="{ color: item.finish_status == 1 ? '#F56C6C' : '#409EFF' }">
                        {{ item.finish_status == 1 ? "暂存" : "提交" }}
                    </div>
                </div>
            </van-list>
        </div>
        <!--		门诊选择-->
        <van-popup v-model="outpatientPopUps" position="bottom">
            <van-search v-model="searchsalesman" placeholder="请输入门诊" @search="getAreaList" />
            <van-picker
                title="选择门诊"
                show-toolbar
                :columns="areaList"
                @confirm="onConfirmArea"
                @cancel="outpatientPopUps = false"
            >
                <template #option="option">
                    {{ option.title }}
                </template>
            </van-picker>
        </van-popup>
        <!--		业务员选择-->
        <van-popup v-model="salesmanPopUpWindow" position="bottom">
            <van-search v-model="searchsalesman" placeholder="请输入业务员" @search="getHospitals" />
            <van-picker
                title="选择业务员"
                show-toolbar
                :columns="getHospitalList"
                @confirm="onConfirmHospita"
                @cancel="salesmanPopUpWindow = false"
            >
                <template #option="option">
                    {{ option.nickname }}
                </template>
            </van-picker>
        </van-popup>
        <!--		日期选择-->
        <!-- <van-popup v-model="dateSelectionPopUp" position="bottom">
			<van-datetime-picker v-model="currentDate" type="date" title="请选择拜访时间" :min-date="minDate" :max-date="maxDate" @cancel="dateSelectionPopUp = false" @confirm="confirmTime" />
		</van-popup> -->
        <van-calendar
            ref="calendar"
            v-model="dateSelectionPopUp"
            title="请选择拜访日期区间"
            color="#50b1c1"
            confirm-text="完成"
            confirm-disabled-text="请选择结束时间"
            :row-height="55"
            :min-date="minDate"
            :max-date="maxDate"
            type="range"
            @confirm="confirmTime"
        />
    </div>
</template>
<script>
import moment from "moment";
import { searchForm } from "../../store/getters";

export default {
    name: "MenuPage",
    data() {
        return {
            year: new Date().getMonth() === 0 ? new Date().getFullYear() - 1 : new Date().getFullYear(),
            month: new Date().getMonth() === 0 ? 12 : new Date().getMonth() + 1,
            day: new Date().getDate(),
            currentDate: new Date(),
            maxDate: new Date(),
            minDate: new Date(2020, 0, 1),
            // 门诊
            outpatient: "门诊",
            // 业务员
            salesman: "业务员",
            // 业务员搜索
            searchsalesman: "",
            // 列表
            list: [],
            form: {
                page: 1, // 当前页数
                pagesize: 10, // 每页数量
                key: "", // 搜索关键词
                user_id: "", //业务员id
                outpatient_id: "", // 门诊id
                start_time: "", // 开始时间,
                end_time: "", //结束时间
            },
            // 总条数
            total: 0,
            // 	门诊选择弹窗
            outpatientPopUps: false,
            // 业务员选择弹窗
            salesmanPopUpWindow: false,
            // 日期选择弹窗
            dateSelectionPopUp: false,
            // 门诊列表
            areaList: [],
            // 业务员列表
            hospitalList: [],
            loading: true,
            finished: false,
            userinfo: {},
        };
    },
    mounted() {
        this.userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
        if (![7, 19].includes(this.userinfo.group_id)) this.form.user_id = this.userinfo?.userinfo?.id;

        //从本地获取有没有业务员历史 如果有 赋值
        let visitlist_salesman = JSON.parse(sessionStorage.getItem("visitlist_salesman"));
        if (visitlist_salesman) {
            this.salesman = visitlist_salesman.salesman;
            this.form.user_id = visitlist_salesman.user_id;
        }

        //从本地获取有没有门诊历史 如果有 赋值
        let visitlist_outpatient = JSON.parse(sessionStorage.getItem("visitlist_outpatient"));
        if (visitlist_outpatient) {
            this.outpatient = visitlist_outpatient.outpatient;
            this.form.outpatient_id = visitlist_outpatient.outpatient_id;
        }

        //从本地获取有没有时间历史 如果有 赋值
        let visitlist_time = JSON.parse(sessionStorage.getItem("visitlist_time"));
        if (visitlist_time) {
            this.form.start_time = visitlist_time.start_time;
            this.form.end_time = visitlist_time.end_time;
            this.year = visitlist_time.year;
            this.month = visitlist_time.month;
            this.day = visitlist_time.day;
        }

        this.getArea();
        this.getHospitals();
        this.onLoad();
    },

    computed: {
        getHospitalList() {
            return this.hospitalList;
        },
        formatTime() {
            return (time, format = "YYYY-MM-DD HH:mm:ss") => {
                return moment(time * 1000).format(format);
            };
        },
        // 根据日期分组
        isFirstDifferentDate() {
            return (timestamp) => {
                // 初始化变量
                let previousDate = null;
                let foundFirst = false;
                // 遍历数据列表
                for (const entry of this.list) {
                    const entryDate = new Date(entry.createtime * 1000).toDateString();
                    // 检查是否遇到了新日期
                    if (entryDate !== previousDate) {
                        // 如果已经跳过了最初的日期段，检查目标时间戳是否是新的第一条
                        if (foundFirst) {
                            if (entry.createtime === timestamp) return true;
                        } else {
                            // 标记已找到跳过后的第一条数据
                            foundFirst = true;
                        }
                        // 更新 previousDate 为当前日期
                        previousDate = entryDate;
                    }
                }
                // 如果没有找到符合条件的时间戳则返回 false
                return false;
            };
        },
    },
    methods: {
        searchForm,
        onLoad() {
            this.finished = false;
            this.form.page = 1;
            this.form.pagesize = 10;
            this.list = [];
            this.getList();
        },
        loadpage() {
            if (this.list.length && this.list.length < this.total) {
                this.form.page += 1;
                this.getList();
            }
        },
        // 获取数据列表
        getList() {
            if (this.finished) return;
            this.loading = true;
            this.$api.visit_lists(this.form).then((res) => {
                this.list = this.list.concat(res?.data?.data);
                this.total = res?.data?.total;
                this.loading = false;
                // 判断是否获取全部数据
                if (this.list.length >= this.total) this.finished = true;
            });
        },
        // 门诊弹窗确认事件
        onConfirmArea(val) {
            this.outpatient = val?.title;
            this.form.outpatient_id = val.id;
            this.outpatientPopUps = !this.outpatientPopUps;

            //将选择的门诊id和name保存到sessionStorage中
            sessionStorage.setItem(
                "visitlist_outpatient",
                JSON.stringify({ outpatient: val?.title, outpatient_id: val.id })
            );

            this.onLoad();
        },
        confirmTime(val) {
            // 转换为时间戳
            this.form.start_time = new Date(val[0]).getTime() / 1000;
            this.form.end_time = new Date(val[1]).getTime() / 1000 + 24 * 60 * 60 - 1;

            this.dateSelectionPopUp = false;
            this.year = new Date(val[0]).getFullYear();
            this.month = new Date(val[0]).getMonth() + 1;
            this.day = new Date(val[0]).getDate();

            //将选择的时间保存到sessionStorage中
            sessionStorage.setItem(
                "visitlist_time",
                JSON.stringify({
                    start_time: this.form.start_time,
                    end_time: this.form.end_time,
                    year: this.year,
                    month: this.month,
                    day: this.day,
                })
            );
            this.onLoad();
        },
        // 业务员弹窗确认事件
        onConfirmHospita(val) {
            this.salesmanPopUpWindow = false;
            if (!val?.id) return;
            this.salesman = val?.nickname;
            this.form.user_id = val.id;

            //将选择的业务员id和name保存到sessionStorage中
            sessionStorage.setItem("visitlist_salesman", JSON.stringify({ salesman: val?.nickname, user_id: val.id }));
            this.onLoad();
        },
        // 门诊列表
        async getArea() {
            const res = await this.$api.all_clinic();
            if (res.data && res.data.length > 0) {
                this.areaList.push(...res.data);
            }
        },
        // 获取业务员列表
        getHospitals(key) {
            this.$api.user_lists({ key }).then((res) => {
                this.hospitalList = res.data;
            });
        },
        // 获取门诊列表
        getAreaList(key) {
            this.$api.all_clinic({ key }).then((res) => {
                if (res.data && res.data.length > 0) {
                    this.areaList = res.data;
                }
            });
        },
        // 跳转详情
        detail(item) {
            this.$router.push({ path: "/visitlogs1", query: { id: item.id, type: "detail" } });
        },
        // 重置搜索
        reset() {
            //如果有 清除sessionStorage中的visitlist_salesman
            if (sessionStorage.getItem("visitlist_salesman")) {
                sessionStorage.removeItem("visitlist_salesman");
            }
            //如果有 清除sessionStorage中的visitlist_outpatient
            if (sessionStorage.getItem("visitlist_outpatient")) {
                sessionStorage.removeItem("visitlist_outpatient");
            }
            //如果有 清除sessionStorage中的visitlist_time
            if (sessionStorage.getItem("visitlist_time")) {
                sessionStorage.removeItem("visitlist_time");
            }

            this.salesman = "业务员";
            this.outpatient = "门诊";
            this.year = new Date().getMonth() === 0 ? new Date().getFullYear() - 1 : new Date().getFullYear();
            this.month = new Date().getMonth() === 0 ? 12 : new Date().getMonth() + 1;
            this.day = new Date().getDate();
            this.$refs.calendar.reset();
            Object.keys(this.form).forEach((key) => {
                this.form[key] = "";
            });
            this.onLoad();
        },
    },
};
</script>

<style scoped lang="scss">
.menu-page {
    position: relative;
    z-index: 2;
    min-height: 100vh;
    background-color: #fff;

    .top-group {
        background-color: #50b1c1;
        height: 50px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        font-size: 16px;
        color: #fff;
        position: sticky;
        top: 0;
        padding: 0 0.4rem;
        z-index: 1;

        .top-select {
            display: flex;
            justify-content: center;
            align-items: center;

            p {
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }

            .van-icon {
                margin-left: 2px;
                font-size: 14px;
            }
        }
    }

    .table-top {
        padding: 0 0.4rem;
        background-color: #f6f6f6;
        height: 50px;
        display: flex;
        // justify-content: space-around;
        align-items: center;
        font-size: 14px;
        color: #000;
        position: sticky;
        top: 50px;
        width: 100%;
        z-index: 1;
        border-bottom: 1px solid #e0e0e0;

        div {
            display: flex;
            justify-content: center;
            align-items: center;

            &:nth-child(1) {
                width: 2rem;
            }

            &:nth-child(2) {
                width: 3rem;
            }

            &:nth-child(3) {
                width: 2rem;
            }

            &:nth-child(4) {
                flex: 1;
            }

            .icon {
                width: 0.35rem;
                margin-left: 6px;
            }
        }
    }

    .table-wrapper {
        .table-row {
            margin: 0 0.4rem;
            min-height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 12px;
            color: #000;
            position: sticky;
            top: 50px;
            width: calc(100% - 0.8rem);
            border-bottom: 1px solid #e0e0e0;

            div {
                word-break: break-all;

                &:nth-child(1) {
                    width: 2rem;
                    text-align: center;
                }

                &:nth-child(2) {
                    width: 3rem;
                    text-align: center;
                }

                &:nth-child(3) {
                    width: 2rem;
                    text-align: center;
                }

                &:nth-child(4) {
                    flex: 1;
                    text-align: center;
                }
            }

            .action {
                color: dodgerblue;
            }
        }

        .table-row-tool {
            padding: 0 0.4rem;
            min-height: 50px;
            background-color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            border-top: 1px solid #e0e0e0;
            z-index: 1;
        }
    }
}
</style>
